class AdminersController < ApplicationController

  # 管理员登录
  def login
    if request.post?
      @adminer = Adminer.find_by_name_and_pass(params[:name], formatpass(params[:pass]))
      if(@adminer != nil)
        # 成功
        session[:adminer] = @adminer
        redirect_to '/admin'
      else
        # 失败
        redirect_to action: 'login', notice: 'login_failure'
      end
    end
  end

  # 管理员退出登录
  def logout
    session[:adminer] = nil
    redirect_to action: 'login', notice: 'logout'
  end

  # GET /adminers
  # GET /adminers.json
  def index
    return unless checkAdmin
    @adminers = Adminer.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @adminers }
    end
  end

  # GET /adminers/1
  # GET /adminers/1.json
  def show
    return unless checkAdmin
    @adminer = Adminer.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @adminer }
    end
  end

  # GET /adminers/new
  # GET /adminers/new.json
  def new
    return unless checkAdmin
    @adminer = Adminer.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @adminer }
    end
  end

  # GET /adminers/1/edit
  def edit
    return unless checkAdmin
    @adminer = Adminer.find(params[:id])
  end

  # POST /adminers
  # POST /adminers.json
  def create
    return unless checkAdmin
    @adminer = Adminer.new(params[:adminer])

    respond_to do |format|
      if @adminer.save
        format.html { redirect_to @adminer, notice: 'Adminer was successfully created.' }
        format.json { render json: @adminer, status: :created, location: @adminer }
      else
        format.html { render action: "new" }
        format.json { render json: @adminer.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /adminers/1
  # PUT /adminers/1.json
  def update
    return unless checkAdmin
    @adminer = Adminer.find(params[:id])

    respond_to do |format|
      if @adminer.update_attributes(params[:adminer])
        format.html { redirect_to @adminer, notice: 'Adminer was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @adminer.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /adminers/1
  # DELETE /adminers/1.json
  def destroy
    return unless checkAdmin
    @adminer = Adminer.find(params[:id])
    @adminer.destroy

    respond_to do |format|
      format.html { redirect_to adminers_url }
      format.json { head :no_content }
    end
  end

private

  ## 格式化密码
  def formatpass(pass)
    v1 = Digest::MD5.hexdigest(pass)
    v2 = v1.reverse
    v2[8, 16]
  end

end
